package com.imooc.miaosha.service.impl;

import com.google.common.collect.Lists;
import com.imooc.miaosha.service.SolrService;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.jdbc.object.SqlQuery;
import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.util.List;

public class SolrServiceImpl implements SolrService {
    HttpSolrClient httpSolrClient;
    private Integer row = 20;

    public SolrServiceImpl(HttpSolrClient httpSolrClient) {
        this.httpSolrClient = httpSolrClient;
    }

    public void setRow(Integer row) {
        this.row = row;
    }


    @Override
    public List<Integer> queryIndex(String val, String indexName, int start) throws IOException, SolrServerException {

        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q", val);
        solrQuery.setRows(this.row);
        solrQuery.setStart(start);
        QueryResponse queryResponse = httpSolrClient.query(solrQuery);
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        List<Integer> idList = Lists.newArrayList();
        for (SolrDocument s : solrDocumentList) {
            idList.add(Integer.parseInt((String) s.get(indexName)));
        }
        return idList;
    }

    @Override
    public void insert(String val, String id) {
        SolrInputDocument document = new SolrInputDocument();
        document.addField("title", val);
        document.addField("id", id);
        try {
            httpSolrClient.add(document);
            httpSolrClient.commit();
            httpSolrClient.close();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
